package com.link510.aitools.services;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.google.common.base.Strings;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.link510.aitools.core.enums.XFVoice;
import com.link510.aitools.core.listen.CWMListener;
import com.orhanobut.logger.Logger;

public class XFCouldUtils extends BaseService {


    private static final String TAG = "TTSUtility";
    // 语音合成对象
    private static SpeechSynthesizer mTts;
    //上下文
    private Context mContext;

    private volatile static XFCouldUtils instance;

    private String ttsAudioPath = "";
    /**
     * 合成回掉监听
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {
            Logger.d(TAG, "开始播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            // TODO 缓冲的进度
            Logger.d(TAG, "缓冲 : " + percent);
        }

        @Override
        public void onSpeakPaused() {
            Logger.d(TAG, "暂停播放");

        }

        @Override
        public void onSpeakResumed() {
            Logger.d(TAG, "继续播放");
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // TODO 说话的进度
            Logger.d(TAG, "合成 : " + percent);
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                Logger.d(TAG, "播放完成");

            } else if (error != null) {
                Logger.d(TAG, error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

        }
    };

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    private XFCouldUtils(Context context) {
        this.mContext = context;
        this.ttsAudioPath = mContext.getExternalCacheDir() + "/msc/tts.wav";
        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this.mContext, code -> {
            if (code != ErrorCode.SUCCESS) {
                Log.d("fjj", "初始化失败,错误码：" + code);
                return;
            }
            Log.d("fjj", "初始化失败,q错误码：" + code);
        });

    }

    public static XFCouldUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (XFCouldUtils.class) {
                if (instance == null) {
                    instance = new XFCouldUtils(context);
                }
            }
        }
        return instance;
    }

    /**
     * 停止语音播报
     */
    public void stopSpeaking() {
        // 对象非空并且正在说话
        if (null != mTts && mTts.isSpeaking()) {
            // 停止说话
            mTts.stopSpeaking();
        }
    }

    /**
     * 判断当前有没有说话
     *
     * @return
     */
    public boolean isSpeaking() {
        if (null != mTts) {
            return mTts.isSpeaking();
        } else {
            return false;
        }
    }

    /**
     * 开始合成
     *
     * @param text
     * @param audoSpeed
     * @param audoPitch
     * @param audoVolume
     */
    public void speaking(String text, String voiceCode, int audoSpeed, int audoPitch, int audoVolume, CWMListener<String> cwmListener) {

        if (Strings.isNullOrEmpty(text)) {
            return;
        }

        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 引擎类型 网络
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置发音人
        mTts.setParameter(SpeechConstant.VOICE_NAME, XFVoice.getVoiceCode(voiceCode).getCode());

        if (audoSpeed >= 0 && audoSpeed <= 100) {
            // 设置语速
            mTts.setParameter(SpeechConstant.SPEED, audoSpeed + "");
        } else {
            // 设置语速
            mTts.setParameter(SpeechConstant.SPEED, "50");
        }

        if (audoPitch >= 0 && audoPitch <= 100) {
            // 设置语速
            mTts.setParameter(SpeechConstant.PITCH, audoPitch + "");
        } else {
            // 设置音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
        }


        if (audoVolume >= 0 && audoVolume <= 100) {
            // 设置语速
            mTts.setParameter(SpeechConstant.VOLUME, audoVolume + "");
        } else {
            // 设置音量
            mTts.setParameter(SpeechConstant.VOLUME, "100");
        }
        // 设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");

        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, mContext.getExternalCacheDir() + "/msc/tts.wav");

        Log.e(TAG, "speaking: " + mContext.getExternalCacheDir() + "/msc/tts.wav");

        int code = mTts.startSpeaking(text, mTtsListener);

        Log.d("fjj", "-----" + code + "++++++++++");

        if (code != ErrorCode.SUCCESS) {
            if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                ToastUtils.showShort("没有安装语音+ code = " + code);
            } else {
                ToastUtils.showShort("语音合成失败,错误码: " + code);
            }

            onErrorAction(cwmListener, code, "语音转换失败");

            return;
        }

        onSuccessAction(cwmListener, "语音转换成功", ttsAudioPath);
    }


}
